package com.lp.biz.member.service.impl;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lp.biz.ComponentService;
import com.lp.biz.identity.mapper.AdvisorMapper;
import com.lp.biz.identity.mapper.AdvisorMemberRelMapper;
import com.lp.biz.identity.mapper.BizIdentityMapper;
import com.lp.biz.identity.mapper.BizIdentityMemberRelMapper;
import com.lp.biz.identity.model.entity.Advisor;
import com.lp.biz.identity.model.entity.AdvisorMemberRel;
import com.lp.biz.identity.model.entity.BizIdentity;
import com.lp.biz.identity.model.entity.BizIdentityMemberRel;
import com.lp.biz.medal.component.MedalFactory;
import com.lp.biz.member.mapper.PensionMapper;
import com.lp.biz.member.mapper.PensionMemberRelMapper;
import com.lp.biz.member.model.entity.Pension;
import com.lp.biz.member.model.entity.PensionMemberRel;
import com.lp.biz.member.model.query.*;
import com.lp.biz.members.mapper.BizMembersMapper;
import com.lp.biz.members.mapper.BizMembersRelMapper;
import com.lp.biz.members.model.entity.BizMembers;
import com.lp.biz.members.model.entity.BizMembersRel;
import com.lp.biz.message.service.BizMessageSystemService;
import com.lp.biz.operations.mapper.BlackListMapper;
import com.lp.biz.member.mapper.UserMapper;
import com.lp.biz.operations.model.entity.BlackList;
import com.lp.biz.member.model.entity.Member;
import com.lp.biz.member.mapper.MemberMapper;
import com.lp.biz.member.model.vo.*;
import com.lp.biz.member.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lp.biz.order.mapper.BizOrderMapper;
import com.lp.biz.order.model.entity.BizOrder;
import com.lp.biz.system.mapper.SysRoleMapper;
import com.lp.biz.system.mapper.SysRoleMemberRelMapper;
import com.lp.biz.system.model.entity.SysRole;
import com.lp.biz.system.model.entity.SysRoleMemberRel;
import com.lp.biz.train.mapper.BizTrainClassMemberRelMapper;
import com.lp.biz.train.model.entity.BizTrainClassMemberRel;
import com.lp.common.component.RedisService;
import com.lp.common.context.ContextHolder;
import com.lp.common.context.UserDetail;
import com.lp.common.entity.PageParams;
import com.lp.common.exception.BaseException;
import com.lp.common.exception.ErrorCodeEnum;
import com.lp.common.utils.CommonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.lp.common.constant.AdvisorConstant.CODE_SILVER_ADVISOR;
import static com.lp.common.constant.CacheConstant.*;
import static com.lp.common.constant.CommonConstant.NEGATE;
import static com.lp.common.constant.CommonConstant.SURE;
import static com.lp.common.constant.IdentityConstant.*;
import static com.lp.common.constant.MembersConst.TYPE_YEAR;
import static com.lp.common.constant.OrderConstant.*;
import static com.lp.common.constant.PensionConstant.*;
import static com.lp.common.utils.Tools.copyPage;
import static com.lp.common.utils.Tools.stripTrailingZeros;

/**
 * @program: backend
 * @description: Member 服务实现类
 * @author Ke.Song
 * @since 2024-05-03 11:30:02
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private RedisService redis;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private MedalFactory medalFactory;

    @Autowired
    private BizOrderMapper orderMapper;

    @Autowired
    private PensionMapper pensionMapper;

    @Autowired
    private AdvisorMapper advisorMapper;

    @Autowired
    private BizMembersMapper membersMapper;

    @Autowired
    private BlackListMapper blackListMapper;

    @Autowired
    private ComponentService componentService;

    @Autowired
    private BizIdentityMapper identityMapper;

    @Autowired
    private BizMembersRelMapper membersRelMapper;

    @Autowired
    private SysRoleMemberRelMapper roleMemberRelMapper;

    @Autowired
    private BizMessageSystemService messageSystemService;

    @Autowired
    private AdvisorMemberRelMapper advisorMemberRelMapper;

    @Autowired
    private PensionMemberRelMapper pensionMemberRelMapper;

    @Autowired
    private BizTrainClassMemberRelMapper classMemberRelMapper;
    
    @Autowired
    private BizIdentityMemberRelMapper identityMemberRelMapper;

    @Override
    public CommonResult getMemberList(String nickName, String phone) {
        List<MemberDropDown> result = new ArrayList<>(6);
        LambdaQueryWrapper<Member> queryWrapper = new QueryWrapper<Member>().lambda().orderByAsc(Member::getId);
        if (StringUtils.isNotBlank(nickName)) {
            queryWrapper.like(Member::getNickName, nickName.trim());
        }
        if (StringUtils.isNotBlank(phone)) {
            queryWrapper.like(Member::getPhone, phone.trim());
        } else {
            queryWrapper.isNotNull(Member::getPhone);
        }
        queryWrapper.isNotNull(Member::getOpenId);
        if (StringUtils.isNotBlank(nickName) || StringUtils.isNotBlank(phone)) {
            for (Member member : memberMapper.selectList(queryWrapper)) {
                result.add(new MemberDropDown(member.getId(), member.getNickName(), member.getPhone()));
            }
        }
        return CommonResult.success(result);
    }

    @Override
    public CommonResult getNormalMemberList(NormalMemberQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        return CommonResult.restPage(memberMapper.getNormalMemberList(query));
    }

    @Override
    public UserDetail getUserDetail(Integer memberId) {
        if (memberId == null) {
            memberId = ContextHolder.getContext().getMemberId();
        }
        UserDetail userDetail = redis.get(USER_DETAIL_KEY + memberId, UserDetail.class);
        if (userDetail == null) {
            userDetail = userMapper.getUserDetail(memberId);
            redis.put(USER_DETAIL_KEY + memberId, userDetail);
        }
        return userDetail;
    }

    @Override
    public CommonResult getReadingMemberList(NormalMemberQuery query) {
        PageInfo<ReadingMemberList> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(query.getPage());
        pageInfo.setPageSize(query.getSize());
        List<ReadingMemberList> readingMemberList = memberMapper.getReadingMemberList(query);
        pageInfo.setTotal(readingMemberList.size());
        pageInfo.setList(readingMemberList.stream()
                .skip((long) query.getSize() * (query.getPage() - 1))
                .limit(query.getSize()).toList());
        return CommonResult.restPage(pageInfo);
    }

    @Override
    public CommonResult getTrainStudent(TrainStudentQuery query) {
        PageInfo<TrainStudentList> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(query.getPage());
        pageInfo.setPageSize(query.getSize());
        List<TrainStudentList> trainStudent = memberMapper.getTrainStudent(query);
        pageInfo.setTotal(trainStudent.size());
        pageInfo.setList(trainStudent.stream()
                .skip((long) query.getSize() * (query.getPage() - 1))
                .limit(query.getSize()).toList());
        return CommonResult.restPage(pageInfo);
    }

    @Override
    public CommonResult getTrainManageList(TrainMemberQuery query, String category) {
        PageInfo<TrainerMembersList> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(query.getPage());
        pageInfo.setPageSize(query.getSize());
        List<TrainerMembersList> trainerList = memberMapper.getTrainManageList(query, category);
        pageInfo.setTotal(trainerList.size());
        pageInfo.setList(trainerList.stream()
                .skip((long) query.getSize() * (query.getPage() - 1))
                .limit(query.getSize()).toList());
        return CommonResult.restPage(pageInfo);
    }

    @Override
    public CommonResult getAdvisors(AdvisorQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        List<AdvisorMemberList> advisors = memberMapper.getAdvisors(query);
        for (AdvisorMemberList advisor : advisors) {
            advisor.setRate(stripTrailingZeros(advisor.getRate()));
        }
        return CommonResult.restPage(advisors);
    }

    @Override
    public CommonResult getMemberDetail(Integer memberId) {
        String s = redis.get(MEMBER_INFO_KEY + memberId);
        MemberDetail detail;
        if (s == null) {
            detail = memberMapper.getMemberDetail(memberId);
            for (BizOrder order : orderMapper.selectList(new QueryWrapper<BizOrder>().lambda()
                    .eq(BizOrder::getMemberId, memberId).eq(BizOrder::getStatus, STATUS_PAID)
                    .orderByAsc(BizOrder::getCreateAt))) {
                detail.setOrderNum(detail.getOrderNum() + 1);
                detail.setTotalAmount(detail.getTotalAmount().add(order.getPayPrice()));
                detail.setLastPayAt(order.getCreateAt());
                if (ObjectUtil.equals(ORDER_TYPE_READING, order.getOrderType())) {
                    detail.setTotalClass(detail.getTotalClass() + 1);
                }
            }
            detail.setDoneClass(classMemberRelMapper.selectList(new QueryWrapper<BizTrainClassMemberRel>().lambda()
                    .eq(BizTrainClassMemberRel::getMemberId, memberId)
                    .eq(BizTrainClassMemberRel::getIsGraduation, SURE))
                    .stream()
                    .map(BizTrainClassMemberRel::getBizTrainClassId)
                    .collect(Collectors.toSet()).size());
            detail.setPhone(DesensitizedUtil.mobilePhone(detail.getPhone()));
            detail.setRealName(DesensitizedUtil.chineseName(detail.getRealName()));
            detail.setName(DesensitizedUtil.chineseName(detail.getName()));
            detail.setCardNo(DesensitizedUtil.bankCard(detail.getCardNo()));
            detail.setIdCard(DesensitizedUtil.idCardNum(detail.getIdCard(), 6, 4));
            detail.setBankPhone(DesensitizedUtil.mobilePhone(detail.getBankPhone()));
            detail.setIdentityList(selectIdentity(memberId));
            detail.setAmountWithdrawal(stripTrailingZeros(detail.getAmountWithdrawal()));
            detail.setMonthWithdrawal(stripTrailingZeros(detail.getMonthWithdrawal()));
            detail.setBalance(stripTrailingZeros(detail.getBalance()));
            detail.setCommissionRate(stripTrailingZeros(detail.getCommissionRate()));
            detail.setTotalAmount(stripTrailingZeros(detail.getTotalAmount()));
            Long l = blackListMapper.selectCount(new QueryWrapper<BlackList>().lambda().eq(BlackList::getMemberId, memberId));
            detail.setIsBlacklist(l == null ? NEGATE: l.intValue());
            redis.put(MEMBER_INFO_KEY + memberId, detail);
        } else {
            detail = JSONUtil.toBean(s, MemberDetail.class);
        }
        return CommonResult.success(detail);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addTrainManage(CreateTrainManage manage) {
        Member member = memberMapper.selectById(manage.getMemberId());
        if (member == null) {
            throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
        }
        redis.delete(MEMBER_INFO_KEY + member.getId());
        LambdaQueryWrapper<BizIdentity> queryWrapper = new QueryWrapper<BizIdentity>().lambda().eq(BizIdentity::getCategory, manage.getCategory());
        if (!manage.getCategory().equals(CLASS_TEACHER)) {
            String typeCode = manage.getTypeCode();
            if (typeCode == null) {
                throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
            } else if (!typeCode.equals(TYPE_READING) && !typeCode.equals(TYPE_WRITING) && !typeCode.equals(TYPE_SPEECH) && !typeCode.equals(TYPE_VOICE)) {
                throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
            } else {
                queryWrapper.eq(BizIdentity::getTypeCode, typeCode);
            }
        }
        List<BizIdentity> bizIdentities = identityMapper.selectList(queryWrapper);
        if (bizIdentities.size() != 1) {
            throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
        }
        BizIdentity identity = bizIdentities.get(0);
        BizIdentityMemberRel rel = identityMemberRelMapper.selectOne(new QueryWrapper<BizIdentityMemberRel>().lambda()
                .eq(BizIdentityMemberRel::getMemberId, member.getId())
                .eq(BizIdentityMemberRel::getBizIdentityId, identity.getId()));
        if (rel == null) {
            rel = new BizIdentityMemberRel();
            rel.setMemberId(member.getId());
            rel.setBizIdentityId(identity.getId());
            rel.setIsDefault(NEGATE);
            rel.setIsEffective(NEGATE);
            rel.setCreateAt(LocalDateTime.now());
            rel.setSource(2);
            identityMemberRelMapper.insert(rel);
            medalFactory.addMedal(member.getId(), identity);
        }
        if (identity.getRate().compareTo(member.getRate()) > 0) {
            member.setRate(identity.getRate());
            memberMapper.updateById(member);
        }
        componentService.setDefault(rel, identity);
        redis.delete(MEMBER_INFO_KEY + member.getId());
        if (manage.getCategory().equals(CLASS_TEACHER)) {
            SysRole role = roleMapper.selectOne(new QueryWrapper<SysRole>().lambda().eq(SysRole::getCode, CLASS_TEACHER));
            if (role != null) {
                SysRoleMemberRel roleMemberRel = roleMemberRelMapper.selectOne(new QueryWrapper<SysRoleMemberRel>().lambda().eq(SysRoleMemberRel::getMemberId, member.getId()).eq(SysRoleMemberRel::getSysRoleId, role.getId()));
                if (roleMemberRel == null) {
                    roleMemberRel = new SysRoleMemberRel();
                    roleMemberRel.setSysRoleId(role.getId());
                    roleMemberRel.setMemberId(member.getId());
                    roleMemberRelMapper.insert(roleMemberRel);
                }
            }
        }
        redis.delete(MEMBER_INFO_KEY + member.getId());
        redis.delete(BIZ_USER_DETAIL_KEY + member.getId());
    }

    @Override
    public CommonResult getMemberOrders(PageParams query, Integer memberId) {
        PageHelper.startPage(query.getPage(), query.getSize());
        List<MemberOrderList> orders = orderMapper.getMemberOrders(memberId);
        for (MemberOrderList order : orders) {
            order.setActualPrice(stripTrailingZeros(order.getActualPrice()));
            order.setPayPrice(stripTrailingZeros(order.getPayPrice()));
        }
        return CommonResult.restPage(orders);
    }

    @Override
    public CommonResult getMemberInvitationList(PageParams query, Integer memberId) {
        PageHelper.startPage(query.getPage(), query.getSize());
        List<Member> members = memberMapper.selectList(new QueryWrapper<Member>().lambda()
                .eq(Member::getInvitation, memberId).orderByDesc(Member::getCreateAt));
        Page<MemberInvitationList> result = copyPage(new Page<>(), members);
        for (Member member : members) {
            result.add(MemberInvitationList.builder(member));
        }
        return CommonResult.restPage(result);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addOrUpdateBlackList(Integer memberId, String reason) {
        Member member = memberMapper.selectById(memberId);
        if (member == null) {
            throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
        }
        Integer operator = ContextHolder.getContext().getMemberId();
        BlackList blackList = blackListMapper.selectOne(new QueryWrapper<BlackList>().lambda().eq(BlackList::getMemberId, memberId));
        redis.delete(MEMBER_INFO_KEY + memberId);
        if (blackList == null) {
            if (StringUtils.isBlank(reason)) {
                throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
            }
            blackList = new BlackList();
            blackList.setMemberId(memberId);
            blackList.setReason(reason);
            blackList.setOperator(operator);
            blackList.setCreateAt(LocalDateTime.now());
            blackListMapper.insert(blackList);
        } else {
            blackListMapper.delete(new QueryWrapper<BlackList>().lambda().eq(BlackList::getMemberId, memberId));
        }
        redis.delete(MEMBER_INFO_KEY + memberId);
    }

    @Override
    public CommonResult getStudyList(PageParams query, Integer memberId) {
        PageHelper.startPage(query.getPage(), query.getSize());
        return CommonResult.restPage(memberMapper.getStudyList(memberId));
    }

    @Override
    public CommonResult getActivityList(PageParams query, Integer memberId) {
        PageHelper.startPage(query.getPage(), query.getSize());
        return CommonResult.restPage(memberMapper.getActivityList(memberId));
    }

    @Override
    public CommonResult getArticleList(PageParams query, Integer memberId) {
        PageHelper.startPage(query.getPage(), query.getSize());
        return CommonResult.restPage(memberMapper.getArticleList(memberId));
    }

    @Override
    public CommonResult getPension(PensionQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        return CommonResult.restPage(pensionMapper.getPension(query));
    }

    @Override
    public CommonResult getPensionMembers(PensionQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        return CommonResult.restPage(pensionMapper.getPensionMembers(query));
    }

    @Override
    public CommonResult getPensionDetail(Integer pensionId, PensionQuery query) {
        query.setPensionId(pensionId);
        PageHelper.startPage(query.getPage(), query.getSize());
        return CommonResult.restPage(pensionMapper.getPensionDetail(query));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void agreePension(Integer detailId, Integer status) {
        pensionHandler(detailId, status);
    }

    private void pensionHandler(Integer detailId, Integer status) {
        PensionMemberRel rel = pensionMemberRelMapper.selectById(detailId);
        if (rel == null || !rel.getStatus().equals(AUDIT_STATUS)) {
            throw new BaseException("明细选择错误");
        }
        if (status.equals(SURE)) {
            rel.setStatus(AUDIT_STATUS_AGREE);
            Member member = memberMapper.selectById(rel.getMemberId());
            addMembersBenefits(member);
            addAdvisorBenefits(member);
            messageSystemService.pensionMemberPass(member.getId());
        } else {
            rel.setStatus(AUDIT_STATUS_REFUSE);
        }
        pensionMemberRelMapper.updateById(rel);
        int auditStatusAgree = 0;
        int auditStatusRefuse = 0;
        Set<Integer> refuseIds = new HashSet<>();
        List<PensionMemberRel> relList = pensionMemberRelMapper.selectList(new QueryWrapper<PensionMemberRel>()
                .lambda().eq(PensionMemberRel::getPensionId, rel.getPensionId()));
        for (PensionMemberRel pensionMemberRel : relList) {
            if (pensionMemberRel.getStatus().equals(AUDIT_STATUS_AGREE)) {
                auditStatusAgree ++;
            } else if (pensionMemberRel.getStatus().equals(AUDIT_STATUS_REFUSE)) {
                refuseIds.add(pensionMemberRel.getMemberId());
                auditStatusRefuse ++;
            }
        }
        if (!relList.isEmpty()) {
            Pension pension = pensionMapper.selectById(rel.getPensionId());
            if (auditStatusAgree == relList.size()) {
                pension.setStatus(LOG_STATUS_DONE);
                messageSystemService.pensionMemberSuccess(pension.getMemberId());
            } else if (auditStatusRefuse == relList.size() || auditStatusAgree + auditStatusRefuse == relList.size()) {
                pension.setStatus(LOG_STATUS_DONE);
                String names = memberMapper.selectList(new QueryWrapper<Member>().lambda().in(Member::getId, refuseIds))
                        .stream().map(Member::getNickName).collect(Collectors.joining(";"));
                messageSystemService.pensionMemberFail(pension.getMemberId(), names);
            }
            pensionMapper.updateById(pension);
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void refusePension(Integer detailId, Integer status) {
        pensionHandler(detailId, status);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateRate(Integer memberId, BigDecimal rate) {
        Member member = memberMapper.selectById(memberId);
        if (member.getRate() == null || member.getRate().compareTo(rate) < 0) {
            int update = memberMapper.update(null, new UpdateWrapper<Member>().lambda().eq(Member::getId, memberId)
                    .isNull(member.getRate() == null, Member::getRate)
                    .eq(member.getRate() != null, Member::getRate, member.getRate())
                    .set(Member::getRate, rate));
            if (update == 0) {
                updateRate(memberId, rate);
            }
        }
    }

    private void setVoiceDefault(BizIdentityMemberRel newRel, BizIdentity newIdentity) {
        // 设置新关系为有效和默认
        newRel.setIsEffective(SURE);
        newRel.setIsDefault(NEGATE);
        redis.delete(USER_DETAIL_KEY + newRel.getMemberId());

        // 查询当前成员已有的有效身份关系
        for (BizIdentityMemberRel rel : identityMemberRelMapper.selectList(new QueryWrapper<BizIdentityMemberRel>()
                .lambda()
                .eq(BizIdentityMemberRel::getMemberId, newRel.getMemberId())
                .eq(BizIdentityMemberRel::getIsEffective, SURE))) {
            // 根据身份id查询对应的身份信息
            BizIdentity exitsIdentity = identityMapper.selectById(rel.getBizIdentityId());
            if (exitsIdentity != null && ObjectUtil.equals(TYPE_VOICE, exitsIdentity.getTypeCode())) {
                if (rel.getBizIdentityId().equals(newRel.getBizIdentityId())) {
                    newRel.setIsEffective(rel.getIsEffective());
                    newRel.setIsDefault(rel.getIsDefault());
                    break;
                } else if (newIdentity.getPreIds() == null) {
                    newRel.setIsEffective(NEGATE);
                    break;
                } else {
                    Set<String> strings = new HashSet<>(Arrays.asList(newIdentity.getPreIds().split(",")));
                    if (strings.contains(String.valueOf(exitsIdentity.getId()))) {
                        identityMemberRelMapper.update(null, new UpdateWrapper<BizIdentityMemberRel>()
                                .lambda()
                                .eq(BizIdentityMemberRel::getMemberId, rel.getMemberId())
                                .eq(BizIdentityMemberRel::getBizIdentityId, rel.getBizIdentityId())
                                .set(BizIdentityMemberRel::getIsDefault, NEGATE)
                                .set(BizIdentityMemberRel::getIsEffective, NEGATE));
                    } else {
                        newRel.setIsEffective(NEGATE);
                        break;
                    }
                }
            }
        }
        redis.delete(USER_DETAIL_KEY + newRel.getMemberId());
    }

    /**
     * 根据成员ID选择身份信息。
     * 此方法用于查询并整理与指定成员ID相关联的身份信息，包括直接关联的身份和作为顾问的身份。
     * 直接关联的身份是指通过BizIdentityMemberRel表关联的身份，而作为顾问的身份是指通过AdvisorMemberRel表关联的顾问身份。
     *
     * @param memberId 成员的ID，用于查询与该成员相关联的身份信息。
     * @return 返回一个包含所有相关身份名称的列表。
     */
    private List<String> selectIdentity(Integer memberId) {
        // 初始化结果列表，用于存储查询到的身份名称。
        List<String> result = new ArrayList<>();
        // 使用HashMap临时存储身份信息，以优化查找效率。
        Map<String, BizIdentity> tempMaps = new LinkedHashMap<>(6);
        // 初始化身份列表，用于存储查询到的所有身份信息。
        List<BizIdentity> identityList = new ArrayList<>();
        // 根据memberId查询与成员直接关联的身份关系列表。
        List<BizIdentityMemberRel> relList = identityMemberRelMapper.selectList(new QueryWrapper<BizIdentityMemberRel>()
                .lambda().eq(BizIdentityMemberRel::getMemberId, memberId)
                .eq(BizIdentityMemberRel::getIsEffective, SURE));
        // 如果关联列表不为空，进一步查询这些关联的身份信息。
        if (!relList.isEmpty()) {
            identityList.addAll(identityMapper.selectList(new QueryWrapper<BizIdentity>().lambda()
                    .in(BizIdentity::getId, relList.stream()
                            .map(BizIdentityMemberRel::getBizIdentityId)
                            .collect(Collectors.toSet()))
                    .orderByAsc(BizIdentity::getId)));
        }
        // 遍历身份列表，将身份信息添加到临时Map中，并进行身份类别检查，避免重复。
        for (BizIdentity identity : identityList) {
            tempMaps.put(identity.getCode(), identity);
            // 检查已添加的身份中是否有与当前身份类别相互冲突的情况，如果有，则移除冲突的身份。
            for (Map.Entry<String, BizIdentity> entry : tempMaps.entrySet()) {
                if (!identity.getCode().equals(entry.getKey())) {
                    if (entry.getValue().getCategory().equals(identity.getCode())) {
                        tempMaps.remove(identity.getCode());
                        break;
                    }
                    if (identity.getCategory().equals(entry.getValue().getCode())) {
                        tempMaps.remove(entry.getValue().getCode());
                        break;
                    }
                }
            }
        }
        // 将临时Map中的身份名称添加到结果列表中。
        tempMaps.forEach((k, v) -> result.add(v.getName()));
        // 查询与成员关联的顾问关系列表。
        List<AdvisorMemberRel> advisorMemberRelList = advisorMemberRelMapper.selectList(
                new QueryWrapper<AdvisorMemberRel>().lambda().eq(AdvisorMemberRel::getMemberId, memberId)
                        .eq(AdvisorMemberRel::getIsEffective, SURE));
        // 如果顾问关系列表不为空，进一步查询这些顾问的信息。
        if (!advisorMemberRelList.isEmpty()) {
            // 查询所有与成员关联的顾问的身份信息，并添加到结果列表中。
            for (Advisor advisor : advisorMapper.selectList(new QueryWrapper<Advisor>().lambda()
                    .in(Advisor::getId, advisorMemberRelList.stream()
                            .map(AdvisorMemberRel::getAdvisorId).collect(Collectors.toSet())))) {
                result.add(advisor.getName());
            }
        }
        return result;
    }

    private void addMembersBenefits(Member member) {
        BizMembers members = membersMapper.selectOne(new QueryWrapper<BizMembers>().lambda().eq(BizMembers::getType, TYPE_YEAR));
        boolean isMembers = member.getIsMembers() != null && !member.getIsMembers().equals(NEGATE);
        LocalDate start = member.getMembersExpiryAt() == null ?  LocalDate.now(): (isMembers ? member.getMembersExpiryAt() : LocalDate.now());
        LocalDate end = start.plusYears(1);
        member.setIsMembers(SURE);
        member.setMembersExpiryAt(end);
        redis.delete(USER_DETAIL_KEY + member.getId());
        BizMembersRel rel = new BizMembersRel();
        rel.setBizMembersId(members.getId());
        rel.setMemberId(member.getId());
        rel.setStartAt(start);
        rel.setEndAt(end);
        rel.setCreateAt(LocalDateTime.now());
        rel.setIsExpired(SURE);
        membersRelMapper.insert(rel);
        messageSystemService.buyMembers(member.getMembersExpiryAt(), member.getId());
        memberMapper.updateById(member);
        redis.delete(USER_DETAIL_KEY + member.getId());
    }

    private void addAdvisorBenefits(Member member) {
        Advisor advisor = advisorMapper.selectOne(new QueryWrapper<Advisor>().lambda().eq(Advisor::getCode, CODE_SILVER_ADVISOR));
        if (member.getRate() == null || member.getRate().compareTo(advisor.getRate()) < 0) {
            member.setRate(advisor.getRate());
        }
        AdvisorMemberRel rel = advisorMemberRelMapper.selectOne(new QueryWrapper<AdvisorMemberRel>().lambda()
                .eq(AdvisorMemberRel::getMemberId, member.getId())
                .eq(AdvisorMemberRel::getIsEffective, SURE));
        redis.delete(USER_DETAIL_KEY + member.getId());
        if (rel == null) {
            rel = new AdvisorMemberRel();
            rel.setMemberId(member.getId());
            rel.setAdvisorId(advisor.getId());
            rel.setIsEffective(SURE);
            rel.setCreateAt(LocalDateTime.now());
            advisorMemberRelMapper.insert(rel);
        } else if (!rel.getAdvisorId().equals(advisor.getId())) {
            if (advisor.getPreIds() != null) {
                Set<String> strings = new HashSet<>(List.of(advisor.getPreIds().split(",")));
                if (strings.contains(rel.getAdvisorId().toString())) {
                    advisorMemberRelMapper.update(null, new UpdateWrapper<AdvisorMemberRel>().lambda()
                            .eq(AdvisorMemberRel::getId, rel.getId()).set(AdvisorMemberRel::getIsEffective, NEGATE));
                    rel = new AdvisorMemberRel();
                    rel.setMemberId(member.getId());
                    rel.setAdvisorId(advisor.getId());
                    rel.setIsEffective(SURE);
                    rel.setCreateAt(LocalDateTime.now());
                    advisorMemberRelMapper.insert(rel);
                }
            }
        }
        memberMapper.updateById(member);
        redis.delete(USER_DETAIL_KEY + member.getId());
    }
}
